package net.javalib.gvmax.post.server;

import java.net.MalformedURLException;
import java.net.URL;

import net.javalib.gvmax.post.client.AppState;
import net.javalib.gvmax.post.client.PostService;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class PostServiceImpl extends RemoteServiceServlet implements PostService {
	private static final long serialVersionUID = 1L;
	UserService userService = UserServiceFactory.getUserService();
	DAO dao = new DAO();

	@Override
	public AppState login(String requestUri) {
		User user = userService.getCurrentUser();
		AppState appState = new AppState();
		if (user != null) {
			String email = user.getEmail().toLowerCase();
			appState.setLoggedIn(true);
			appState.setEmailAddress(email);
			appState.setNickname(user.getNickname());
			appState.setIsAdmin(userService.isUserAdmin());
			appState.setLogoutUrl(userService.createLogoutURL(requestUri));
			appState.setPostUrl(dao.getPostUrl(email));
		} else {
			appState.setLoggedIn(false);
			appState.setLoginUrl(userService.createLoginURL(requestUri));
		}
		return appState;
	}
	
	@Override
	public void setPostUrl(String url) throws IllegalArgumentException {
		try {
			new URL(url);
		} catch (MalformedURLException e) {
			throw new IllegalArgumentException("Invalid URL, make sure it starts with http:");
		}
		User user = userService.getCurrentUser();
		String email = user.getEmail().toLowerCase();
		dao.setPostUrl(email, url);
	}
	
}
